package com.fading.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.fading.common.utils.HttpUtils;
import com.fading.mall.auth.feign.MemberFeignService;
import com.fading.mall.auth.vo.GiteeAccessToken;
import com.fading.mall.auth.vo.GiteeUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
@ConfigurationProperties(prefix = "spring.cloud.auth")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;
    private String client_id;
    private String redirect_uri;
    private String client_secret;

    @GetMapping("/gitee/success")
    public String gitee(@RequestParam("code") String code) throws Exception {
        log.debug("code {}", code);
        log.debug("笨笨 {}", "123");
        Map<String,String> bodys = new HashMap<>();
        bodys.put("grant_type","authorization_code");
        bodys.put("code",code);
        bodys.put("client_id","5a97d951124683c5211b49c7ba9f5925b299f5b440353eb83193d7bb8d8e67ba");
        bodys.put("redirect_uri","http://auth.fading.com/gitee/success");
        bodys.put("client_secret","66c5889639157c3eb7efd465ff0d9b1e23cd034c3f82c5f35a50fb86bba2ec6d");
        //1.根据code换取GiteeAccessToken;
        HttpResponse response_GiteeAccesstoken = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap(), new HashMap(), bodys);

        //处理返回值
        if(response_GiteeAccesstoken.getStatusLine().getStatusCode() == 200){
            //获取到了GiteeAccessToken
            String tokenJson = EntityUtils.toString(response_GiteeAccesstoken.getEntity());
            GiteeAccessToken token = JSON.parseObject(tokenJson, GiteeAccessToken.class);
            //根据Token，通过查询Gitee Open Api获取用户信息
            Map<String,String> query = new HashMap<>();
            query.put("access_token", token.getAccess_token());
            HttpResponse response_userInfo = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap(), query);
            String giteeUserInfoJson = EntityUtils.toString(response_userInfo.getEntity());
            GiteeUserInfo giteeUserInfo = JSON.parseObject(giteeUserInfoJson, GiteeUserInfo.class);

            //登录或者注册这个社交用户
            //1.当前用户如果是第一次进入网站，就自动注册（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）

        }else {
            return "redirect:http://auth.fading.com/login.html";
        }

        //2.登录成功后跳回首页
        return "redirect:http://fading.com";
    }

}
